import React from 'react';
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { ApolloLink, concat } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { onError } from 'apollo-link-error';
import { setContext } from "apollo-link-context";
import { RetryLink } from "apollo-link-retry";
import { StyleSheet, Text, View } from 'react-native';
import { StackNavigator, TabNavigator, TabBarBottom } from 'react-navigation';
import { primaryColor } from './utils';
import LoginPage from './LoginPage';
import JobPage from './JobPage';
import HistoryPage from './HistoryPage';
import MePage from './MePage';
import PrinterPage from './PrinterPage';
import CollectOrderPage from './CollectOrderPage';
import OrderDetailPage from './OrderDetailPage';
import LaundryPricingPage from './LaundryPricingPage';
import CheckoutOverviewPage from './CheckoutOverviewPage';
import CheckoutPaymentPage from './CheckoutPaymentPage';
import OrderNotePage from './OrderNotePage';
import BagScanPage from './BagScanPage';
import OrderHistoryPage from './OrderHistoryPage';
import CheckoutDatePage from './CheckoutDatePage';
import ItemCheckPage from './ItemCheckPage';
import PickupDeliveryFailedPage from './PickupDeliveryFailedPage';
import ContactCustomerPage from './ContactCustomerPage';
import BagCheckPage from './BagCheckPage';
import StoragePage from './StoragePage';
import StoreCheckInPage from './StoreCheckInPage';
import StoreMovePage from './StoreMovePage';
import StoreEditPage from './StoreEditPage';
import AssignFactoryPage from './AssignFactoryPage';
import LaundryCompletePage from './LaundryCompletePage';
import JobPollPage from './JobPollPage';
import MyJobPage from './MyJobPage';
import SendSMSPage from './SendSMSPage';
import FactoryAssignPage from './FactoryAssignPage';
import CheckerMainPage from './CheckerMainPage';
import PhotoUploadPage from './PhotoUploadPage';
import { HOST, displayInChinese, toast } from './utils';
import { getLoginToken } from './clientStorage';

const MainPage = TabNavigator({
  Job: { screen: JobPage },
  History: { screen: HistoryPage },
  Printer: { screen: PrinterPage },
  Me: { screen: MePage },
}, {
  initialRouteName: 'Job',
  swipeEnabled: true,
  animationEnabled: false,
  lazy: true,
  // tabBarComponent: TabBarBottom,
  // tabBarPosition: 'bottom',
  tabBarOptions: {
    activeTintColor: primaryColor,
    inactiveTintColor: 'gray',
    style: {
      backgroundColor: 'white',
    },
    indicatorStyle: {
      backgroundColor: primaryColor,
    }
  }
});

const CleanerMainPage = TabNavigator({
  MyJob: { screen: MyJobPage },
  JobPoll: { screen: JobPollPage },
  Me: { screen: MePage },
}, {
  initialRouteName: 'MyJob',
  swipeEnabled: true,
  animationEnabled: false,
  lazy: true,
  // tabBarComponent: TabBarBottom,
  // tabBarPosition: 'bottom',
  tabBarOptions: {
    activeTintColor: primaryColor,
    inactiveTintColor: 'gray',
    style: {
      backgroundColor: 'white',
    },
    indicatorStyle: {
      backgroundColor: primaryColor,
    }
  }
});

const FactoryMainPage = TabNavigator({
  BagCheck: { screen: BagCheckPage },
  ItemCheck: { screen: ItemCheckPage },
  LaundryComplete: { screen: LaundryCompletePage },
  Sotrage: { screen: StoragePage },
  Settings: { screen: MePage },
}, {
  initialRouteName: 'BagCheck',
  swipeEnabled: true,
  animationEnabled: false,
  lazy: true,
  // tabBarComponent: TabBarBottom,
  // tabBarPosition: 'bottom',
  tabBarOptions: {
    activeTintColor: primaryColor,
    inactiveTintColor: 'gray',
    style: {
      backgroundColor: 'white',
    },
    indicatorStyle: {
      backgroundColor: primaryColor,
    }
  }
});

const ApplicationStack = StackNavigator({
  Login: { screen: LoginPage },
  Main: { screen: MainPage },
  CleanerMain: { screen: CleanerMainPage },
  FactoryMain: { screen: FactoryMainPage },
  CheckerMain: { screen: CheckerMainPage },
  CollectOrder: { screen: CollectOrderPage },
  OrderDetail: { screen: OrderDetailPage },
  LaundryPricing: { screen: LaundryPricingPage },
  CheckoutOverview: { screen: CheckoutOverviewPage },
  OrderNote: { screen: OrderNotePage },
  PickupDeliveryFailed: { screen: PickupDeliveryFailedPage },
  BagScan: { screen: BagScanPage },
  OrderHistory: { screen: OrderHistoryPage },
  CheckoutPayment: { screen: CheckoutPaymentPage },
  ContactCustomer: { screen: ContactCustomerPage },
  StoreCheckIn: { screen: StoreCheckInPage },
  StoreMove: { screen: StoreMovePage },
  StoreEdit: { screen: StoreEditPage },
  AssignFactory: { screen: AssignFactoryPage },
  Printer: { screen: PrinterPage },
  SendSMS: { screen: SendSMSPage },
  FactoryAssign: { screen: FactoryAssignPage },
  PhotoUpload: { screen: PhotoUploadPage },
  CheckoutDeliveryDate: { screen: CheckoutDatePage,
    navigationOptions: ({navigation, screenProps}) => ({ title: `${screenProps.chinese?`选择${['laundry','premiumlaundry'].indexOf(navigation.state.params.type)>=0?'递送':'服务'}时间`:`${['laundry','premiumlaundry'].indexOf(navigation.state.params.type)>=0?'Delivery':'Service'} Date`} (${navigation.state.params.stepIndex+1}/${navigation.state.params.stepper.length})` }) },
}, {
  initialRouteName: 'Login',
  initialRouteParams: {
    // storeId: 'U3RvcmU6OTg=',
    // title: 'RUIQITEST'
  },
  navigationOptions: () =>  {
    return {
      headerTintColor: primaryColor,
      headerStyle: {
        backgroundColor: 'white',
      }
    };
  }
});

export default class App extends React.Component {
  constructor(props) {
    super(props);

    const authMiddleware = setContext((operation, { headers }) =>
      getLoginToken().then(token => {
        return {
          headers: {
            ...headers,
            authorization: token?`Bearer ${token}`:null,
            "x-launguage": displayInChinese()?'chinese':'english'
          }
        };
      })
    );

    const errorLink = onError(({ graphQLErrors, networkError }) => {
      console.log(graphQLErrors);
      console.log(networkError);
    });

    const client = new ApolloClient({
      link: ApolloLink.from([
        new RetryLink({
          delay: {
            initial: 300,
            max: Infinity,
            jitter: true,
          },
          attempts: {
            max: 5,
            retryIf: (error, _operation) => {
              console.log(error);
              if (error) {
                toast(`Network error, retrying...`);
              }

              return !!error;
            },
          }
        }),
        authMiddleware,
        errorLink,
        new HttpLink({ uri: `${HOST}/graphql` }),
      ]),
      cache: new InMemoryCache()
    });

    this.state = {
      client,
      chinese: displayInChinese()
    };
  }
  resetStore = () => {
    return this.state.client.resetStore();
  }
  render() {
    return (
      <ApolloProvider client={this.state.client}>
        <ApplicationStack screenProps={{resetStore:this.resetStore, chinese: this.state.chinese}}/>
      </ApolloProvider>
    );
  }
}
